package com.gzc.just.play.last.war.loginserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.loginserver.service.AuthService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 令牌验证处理器
 * 处理令牌验证请求
 */
@Component
public class TokenValidationHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(TokenValidationHandler.class);
    
    @Autowired
    private AuthService authService;
    
    private static final int TOKEN_VALIDATION = 4004;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从消息中解析令牌
        String token = extractToken(message);
        
        // 验证输入
        if (token == null || token.trim().isEmpty()) {
            sendTokenValidationResponse(ctx, null, false, "Token is required");
            return;
        }
        
        // 验证令牌
        Map<String, Object> validationResult = authService.validateToken(token);
        
        // 检查验证结果
        boolean success = (Boolean) validationResult.getOrDefault("valid", false);
        String messageStr = (String) validationResult.getOrDefault("message", "Token validation failed");
        
        // 发送验证响应
        if (success) {
            // 令牌有效，保存用户ID到通道上下文
            Long userId = (Long) validationResult.get("userId");
            io.netty.util.AttributeKey<Long> userIdKey = io.netty.util.AttributeKey.valueOf("userId");
            ctx.channel().attr(userIdKey).set(userId);
            
            logger.info("Token validation successful for user ID: {}", userId);
        } else {
            logger.warn("Token validation failed");
        }
        
        sendTokenValidationResponse(ctx, validationResult, success, messageStr);
    }
    
    private String extractToken(Object message) {
        // 实际实现中应该从消息对象中解析令牌
        // 这里返回示例值
        return "sample-jwt-token";
    }
    
    private void sendTokenValidationResponse(ChannelHandlerContext ctx, Map<String, Object> validationResult, 
                                          boolean success, String message) {
        // 实际实现中应该构造并发送令牌验证响应消息
        logger.info("Sending token validation response: success={}, message={}", success, message);
        
        // 示例：打印验证结果内容（实际实现中应该将结果序列化为响应消息）
        if (success && validationResult != null) {
            logger.debug("Token validation result content:");
            for (Map.Entry<String, Object> entry : validationResult.entrySet()) {
                logger.debug("{}: {}", entry.getKey(), entry.getValue());
            }
        }
    }

    @Override
    public int getMessageId() {
        return TOKEN_VALIDATION;
    }
    
    @Override
    public String getName() {
        return "TokenValidationHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}